package com.caopeng.achievementmanagement.controller;

import com.caopeng.achievementmanagement.mapper.UserMapper;
import com.caopeng.achievementmanagement.pojo.User;
import com.caopeng.achievementmanagement.service.UserService;
import com.caopeng.achievementmanagement.service.UserServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;

/**
 * @author Crescent_P
 * @date 2021-12-05 9:16
 */
@Controller
public class UserController {
    @Autowired
    private UserService userService;

    // 跳转到登录页面
    @RequestMapping("/toLogin")
    public String toLogin(){
        return "page-login";
    }

    // 登录,之后跳转到主页面
    @PostMapping("/login")
    public String login(@RequestParam String username,
                        @RequestParam String password,
                        HttpSession session,
                        RedirectAttributes attributes){
        User user = userService.getByUserNameAndPassword(username, password);
        // 没有此用户
        if(user == null){
            attributes.addFlashAttribute("msg","用户名或密码错误");
            return "redirect:/toLogin";
        }
        session.setAttribute("user",user);
        return "redirect:/";
    }

    // 跳转到注册页面
    @GetMapping("/toRegister")
    public String toRegister(){
        return "page-register";
    }

    // 注册
    @PostMapping("/register")
    public String register(
            User user,
            HttpSession session){
        userService.addUser(user);
        // 为什么是跳到登录页面呢，是为了得到user的id
        return "redirect:/toLogin";
    }
}
